package org.black.phoneUtility.app.activity;

import java.io.File;
import java.io.IOException;

import org.black.phoneUtility.R;
import org.black.phoneUtility.app.fragment.RestoreFileExploreFragment;
import org.black.phoneUtility.database.sqlite.PhoneUtilitySQLiteOpenHelper;
import org.black.phoneUtility.util.database.backupRestore.BackupRestoreUtility;
import org.black.phoneUtility.util.database.backupRestore.exception.DatabaseVersionDoesNotMatchException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

public class RestoreActivity extends Activity {
	private static final String LOG_TAG = RestoreActivity.class.getName();
	private static final int REQUEST_CODE_FOR_RESTORE_FILE_PATH = 16386;
	private String restoreFilePath = null;

	private ProgressDialog restoreProgressDialog = null;

	private AlertDialog.Builder resultBuilder = null;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CODE_FOR_RESTORE_FILE_PATH) {
			if (data != null) {
				String filePath = data
						.getStringExtra(RestoreFileExploreFragment.RESULT_FILE_PATH);
				if (TextUtils.isEmpty(filePath) == false) {
					restoreFilePath = filePath;
					((TextView) findViewById(R.id.restoreMainRestoreFilePathTextView))
							.setText(restoreFilePath);
				}
			}
		}
	}

	@Override
	public void onBackPressed() {
		this.finish();
		this.overridePendingTransition(R.animator.left_slide_enter,
				R.animator.left_slide_exit);
	}

	@Override
	public void onContentChanged() {
		super.onContentChanged();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		getActionBar().setDisplayHomeAsUpEnabled(true);
		setTitle(R.string.restore_main_title);
		setContentView(R.layout.restore_main);
		Button restoreMainFileButton = (Button) findViewById(R.id.restoreMainFileButton);
		restoreMainFileButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(RestoreActivity.this,
						RestoreFileExploreActivity.class);
				Bundle bundle = new Bundle();
				intent.putExtras(bundle);
				startActivityForResult(intent,
						REQUEST_CODE_FOR_RESTORE_FILE_PATH);
				overridePendingTransition(R.animator.right_slide_enter,
						R.animator.right_slide_exit);
			}
		});
		SharedPreferences sharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		String theLatestBackupFilePath = sharedPreferences
				.getString(
						getString(R.string.preference_backup_and_restore_the_last_backup_file_path),
						null);
		if (restoreFilePath == null) {
			if (TextUtils.isEmpty(theLatestBackupFilePath) == false) {
				File destinationFile = new File(theLatestBackupFilePath);
				if (destinationFile.isFile() == false) {
					resultBuilder
							.setMessage(R.string.restore_main_restore_result_dialog_restore_please_choose_a_file);
					resultBuilder.show();
					return;
				} else {
					restoreFilePath = destinationFile.getAbsolutePath();
					((TextView) findViewById(R.id.restoreMainRestoreFilePathTextView))
							.setText(restoreFilePath);
				}
			}
		}
		Button restoreMainrestoreButton = (Button) findViewById(R.id.restoreMainrestoreButton);
		restoreMainrestoreButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				restoreProgressDialog.show();
				if (TextUtils.isEmpty(restoreFilePath) == true) {
					restoreProgressDialog.dismiss();
					resultBuilder
							.setMessage(R.string.restore_main_restore_result_dialog_restore_please_choose_a_file);
					resultBuilder.show();
					return;
				}

				CheckBox restoreOptionsSmsReplyCheckBox = (CheckBox) findViewById(R.id.restoreMainrestoreOptionsSmsReplyCheckBox);
				boolean restoreSmsReply = restoreOptionsSmsReplyCheckBox
						.isChecked();

				CheckBox restoreOptionsSmsScheduleCheckBox = (CheckBox) findViewById(R.id.restoreMainrestoreOptionsSmsScheduleCheckBox);
				boolean restoreSmsSchedule = restoreOptionsSmsScheduleCheckBox
						.isChecked();

				File sourceFile = new File(restoreFilePath);
				File databaseFile = getDatabasePath(PhoneUtilitySQLiteOpenHelper.DATABASE_NAME);

				try {
					BackupRestoreUtility.restoreDatabase(RestoreActivity.this,
							sourceFile, databaseFile, true, restoreSmsReply,
							restoreSmsSchedule);
				} catch (IOException e) {
					Log.e(LOG_TAG, "I/O Error", e);
					restoreProgressDialog.dismiss();
					resultBuilder
							.setMessage(R.string.restore_main_restore_result_dialog_file_operation_error);
					resultBuilder.show();
					return;
				} catch (DatabaseVersionDoesNotMatchException e) {
					Log.e(LOG_TAG, "Version numbers do not match!", e);
					restoreProgressDialog.dismiss();
					resultBuilder
							.setMessage(R.string.restore_main_restore_result_dialog_database_version_do_not_match);
					resultBuilder.show();
					return;
				} catch (SQLiteException e) {
					Log.e(LOG_TAG, "SQLite Exception!", e);
					restoreProgressDialog.dismiss();
					resultBuilder
							.setMessage(R.string.restore_main_restore_result_dialog_file_operation_error);
					resultBuilder.show();
					return;
				}
				restoreProgressDialog.dismiss();
				resultBuilder
						.setMessage(R.string.restore_main_restore_result_dialog_restore_complete);
				resultBuilder.show();
			}
		});
		Button restoreMainCancelButton = (Button) findViewById(R.id.restoreMainCancelButton);
		restoreMainCancelButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		this.restoreProgressDialog = new ProgressDialog(RestoreActivity.this,
				ProgressDialog.STYLE_SPINNER);
		this.restoreProgressDialog
				.setTitle(R.string.restore_main_restore_dialog_title);
		this.restoreProgressDialog
				.setMessage(getString(R.string.restore_main_restore_dialog_message));
		this.resultBuilder = new AlertDialog.Builder(this);
		this.resultBuilder.setPositiveButton(android.R.string.ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.restoreProgressDialog.cancel();
		this.restoreProgressDialog.dismiss();
		this.restoreProgressDialog = null;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
